package cn.edu.zjut.mina.util;

import java.nio.charset.Charset;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import cn.edu.zjut.mina.protocal.JAbsMessageProtocal;
import cn.edu.zjut.mina.protocal.JMessageProtocalReq;
import cn.edu.zjut.mina.protocal.JMessageProtocalRes;

public class HEncoder implements ProtocolEncoder {
	private final static Log log = LogFactory.getLog(HEncoder.class);

	private final Charset charset;

	public HEncoder(Charset charset) {
		this.charset = charset;
	}

	public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {

		// new buf  
	    IoBuffer buf=IoBuffer.allocate(2048).setAutoExpand(true);
	    String data = "";
	    if(message instanceof JMessageProtocalReq) {// 请求协议  
	      JMessageProtocalReq mpReq=(JMessageProtocalReq)message;   
	      data = GsonUtils.beanToJson(mpReq);
	    } else if(message instanceof JMessageProtocalRes) {// 响应协议  
	      JMessageProtocalRes mpRes=(JMessageProtocalRes)message;  
	      data = GsonUtils.beanToJson(mpRes);
	    }  
	    buf.putString(data, charset.newEncoder());
	    buf.flip();  
	    out.write(buf);  
	}

	public void dispose(IoSession session) throws Exception {
		log.info("Dispose called,session is " + session);
	}
}
